import { serviceUnauthorized } from "@/api/modules/system/license";
import { getUser } from "@/api/modules/user";
import { LOGIN_URL, ROUTER_WHITE_LIST } from "@/config/config";
import NProgress from "@/config/nprogress";
import { version } from "@/hooks/useSystem";
import { initDynamicRouter } from "@/routers/modules/dynamicRouter";
import { staticRouter } from "@/routers/modules/staticRouter";
import { GlobalStore } from "@/stores";
import { AuthStore } from "@/stores/modules/auth";
import { GetQueryString } from "@/utils/util";
import { ElMessage } from "element-plus";
import { createRouter, createWebHashHistory } from "vue-router";
import { RouterPath } from "@/enums/routerPath";
import mittBus from "@/utils/mittBus";
import { PublicStore } from "@/stores/modules/public";

/**
 * @description 动态路由参数配置简介
 * @param path ==> 菜单路径
 * @param name ==> 菜单别名
 * @param redirect ==> 重定向地址
 * @param component ==> 视图文件路径
 * @param meta ==> 菜单信息
 * @param meta.icon ==> 菜单图标
 * @param meta.title ==> 菜单标题
 * @param meta.activeMenu ==> 当前路由为详情页时，需要高亮的菜单
 * @param meta.isLink ==> 是否外链
 * @param meta.isHide ==> 是否隐藏
 * @param meta.isFull ==> 是否全屏(示例：数据大屏页面)
 * @param meta.isAffix ==> 是否固定在 tabs nav
 * @param meta.isKeepAlive ==> 是否缓存
 * */
const router = createRouter({
	history: createWebHashHistory(),
	routes: [...staticRouter],
	strict: false,
	scrollBehavior: () => ({ left: 0, top: 0 })
});

/**
 * @description 路由拦截 beforeEach
 * */
router.beforeEach(async (to, from, next) => {
	const publicStore = PublicStore();
	const globalStore = GlobalStore();

	let token = "";
	if (to.query.token) {
		token = to.query.token as string;
		delete to.query.token;
	} else if (window.frames.length != parent.frames.length) {
		const href = new URL(window.location.href);
		let params = href.hash.replace(/\#\/.*\?/, "").split("&");
		let tokenData = params.find(item => item.startsWith("token="));
		token = tokenData?.replace("token=", "") || "";
	}
	if (token) {
		//1、token转存
		publicStore.setToken(token);
		delete to.query.token;

		//2、获取用户信息
		let { result } = await getUser();
		let userInfo: User.UserInfo = { ...result, userId: result.id, status: result.status };
		publicStore.setUserInfo(userInfo);
	}
	console.log("from", from.path, "to", to.path);

	// 1.NProgress 开始
	NProgress.start();

	// 2.动态设置标题
	const title = (globalStore.setting.systemName || import.meta.env.VITE_GLOB_APP_TITLE).trim();
	document.title = to.meta.title ? `${to.meta.title}${title ? " - " + title : ""}` : title;
	// 3.判断是访问登陆页，有 Token 就在当前页面，没有 Token 重置路由并放行到登陆页
	if (to.path === LOGIN_URL) {
		resetRouter();
		return next();
	}
	//授权判断
	if (to.path != LOGIN_URL && to.path != RouterPath.serviceAuth) {
		let res = await serviceUnauthorized({});
		if (res.code == 200) {
			ElMessage.closeAll();
			if (res.result.unAuthorized) {
				ElMessage({
					offset: 50,
					duration: 0,
					message: h("p", null, [
						h("span", null, res.result.message),
						h(
							"i",
							{
								style: "color: teal;cursor:pointer",
								onClick: () => {
									mittBus.emit(RouterPath.serviceAuth);
								}
							},
							"未授权详情"
						)
					]),
					type: "warning"
				});
			}
		}
	} else {
		ElMessage.closeAll();
	}

	// 4.判断访问页面是否在路由白名单地址中，如果存在直接放行
	if (ROUTER_WHITE_LIST.includes(to.path)) return next();

	// 5.判断是否有 Token，没有重定向到 login
	if (!publicStore.token) {
		const param = {} as any;
		if (router.currentRoute.value.fullPath != "/" && router.currentRoute.value.path != LOGIN_URL) {
			param.redirect = encodeURIComponent(router.currentRoute.value.fullPath);
		}
		return next({
			path: LOGIN_URL,
			replace: true,
			query: param
		});
	}

	// 6.如果没有菜单列表，就重新请求菜单列表并添加动态路由
	const authStore = AuthStore();
	authStore.setRouteName(to.name as string);
	if (!authStore.authMenuListGet.length) {
		await initDynamicRouter();

		return next({ ...to, replace: true });
	}
	// 如果有重定向路由，则重定向到目录路由
	if (GetQueryString().redirect) {
		const url = decodeURIComponent(from.query.redirect as string);
		if (to.path != url.split("?")[0]) {
			const param = GetQueryString(url);
			if (!authStore.verifyMenu(url.split("?")[0])) {
				next();
			} else {
				return next({ path: decodeURIComponent(from.query.redirect as string), query: param });
			}
		}
	}
	// 版本更新与刷新;
	let APP_VER = version();
	if (from.path != "/login" && globalStore.currentVersion != APP_VER) {
		// ElMessageBox.confirm("发现新版本，是否刷新页面?", "系统提示", {
		// 	confirmButtonText: "确定",
		// 	cancelButtonText: "取消",
		// 	type: "warning"
		// }).then(async () => {
		globalStore.setCurrentVersion(APP_VER);
		location.reload();
		// });
	} else if (!globalStore.currentVersion || from.path == "/login") {
		globalStore.setCurrentVersion(APP_VER);
	}

	if (from.path == LOGIN_URL && to.path == "/404") {
		//登录跳转的主页无效，强制调整到第一个菜单
		let defaultOath = authStore.authMenuListGet[0].children?.[0]?.path || authStore.authMenuListGet[0].path;
		return next({ path: defaultOath, replace: true });
	}
	// 7.正常访问页面
	next();
});

/**
 * @description 重置路由
 * */
export const resetRouter = () => {
	const authStore = AuthStore();
	authStore.flatMenuListGet.forEach(route => {
		const { name } = route;
		if (name && router.hasRoute(name)) router.removeRoute(name);
	});
};

/**
 * @description 路由跳转结束
 * */
router.afterEach(() => {
	NProgress.done();
});

/**
 * @description 路由跳转错误
 * */
router.onError(error => {
	NProgress.done();
	console.warn("路由错误", error.message);
});

export default router;
